package controller

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "{{.ProjectModule}}/models"
    "{{.ProjectModule}}/service"
)

type {{.StructName}}Controller struct {
    Service *service.{{.StructName}}Service
}

func New{{.StructName}}Controller(service *service.{{.StructName}}Service) *{{.StructName}}Controller {
    return &{{.StructName}}Controller{Service: service}
}

func (ctl *{{.StructName}}Controller) Create(c *gin.Context) {
    var {{.VarName}} models.{{.StructName}}
    if err := c.ShouldBindJSON(&{{.VarName}}); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.Create{{.StructName}}(&{{.VarName}}); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"data": {{.VarName}}})
}

func (ctl *{{.StructName}}Controller) GetAll(c *gin.Context) {
    {{.VarName}}s, err := ctl.Service.GetAll{{.StructName}}s()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"data": {{.VarName}}s})
}

func (ctl *{{.StructName}}Controller) GetByID(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    {{.VarName}}, err := ctl.Service.Get{{.StructName}}ByID(uint(id))
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"data": {{.VarName}}})
}

func (ctl *{{.StructName}}Controller) Update(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    var {{.VarName}} models.{{.StructName}}
    if err := c.ShouldBindJSON(&{{.VarName}}); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.Update{{.StructName}}(uint(id), &{{.VarName}}); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "updated successfully"})
}

func (ctl *{{.StructName}}Controller) Delete(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    if err := ctl.Service.Delete{{.StructName}}(uint(id)); err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "deleted successfully"})
}